import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Favorite } from './entities/favorite.entity';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { QueryFavoriteDto } from './dto/query-favorite.dto';
import { Goods } from '../goods/entities/goods.entity';

@Injectable()
export class FavoriteService {
  @InjectRepository(Favorite)
  private favoriteRepository: Repository<Favorite>;

  @InjectRepository(Goods)
  private goodsRepository: Repository<Goods>;

  async create(createFavoriteDto: CreateFavoriteDto, userId: number) {
    const { goodsId } = createFavoriteDto;

    const goods = await this.goodsRepository.findOne({
      where: { id: goodsId },
    });

    if (!goods) {
      throw new HttpException('商品不存在', HttpStatus.BAD_REQUEST);
    }

    const existFavorite = await this.favoriteRepository.findOne({
      where: {
        goods: { id: goodsId },
        user: { id: userId },
      },
    });

    if (existFavorite) {
      throw new HttpException('已经收藏过了', HttpStatus.BAD_REQUEST);
    }

    const favorite = new Favorite();
    favorite.goods = goods;
    favorite.user = { id: userId } as any;

    try {
      await this.favoriteRepository.save(favorite);
      return '收藏成功';
    } catch (e) {
      throw new HttpException('收藏失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findAll(queryFavoriteDto: QueryFavoriteDto, userId: number) {
    const { pageNum = 1, pageSize = 10 } = queryFavoriteDto;

    const skipCount = (pageNum - 1) * pageSize;

    const [favorites, total] = await this.favoriteRepository.findAndCount({
      where: {
        user: { id: userId },
      },
      skip: skipCount,
      take: pageSize,
      relations: ['goods', 'goods.seller'],
      order: {
        createTime: 'DESC',
      },
    });

    return {
      favorites,
      total,
    };
  }

  async remove(goodsId: number, userId: number) {
    const favorite = await this.favoriteRepository.findOne({
      where: {
        goods: { id: goodsId },
        user: { id: userId },
      },
    });

    if (!favorite) {
      throw new HttpException('收藏不存在', HttpStatus.BAD_REQUEST);
    }

    try {
      await this.favoriteRepository.remove(favorite);
      return '取消成功';
    } catch (e) {
      throw new HttpException('取消失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
